package com.szl.group.service.impl;


import com.szl.group.common.model.ApiCommonModel;
import com.szl.group.common.model.R;
import com.szl.group.service.DispatcherHandler;
import com.szl.group.service.HandlerService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@Component
public class ApiServiceDispathcer implements /*ApplicationContextAware,*/InitializingBean, DispatcherHandler {


    private Map<String, HandlerService> handlersMap;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        //  orderHandleMap = applicationContext.getBeansOfType(HanderService.class);
    }

    /*  @Autowired
      public void setOrderHandleMap(List<OrderHandler> orderHandlers) {


          // 注入各种类型的订单处理类
        *//*  orderHandleMap = orderHandlers.stream().collect(
                Collectors.toMap(orderHandler -> AnnotationUtils.findAnnotation(orderHandler.getClass(), OrderHandlerType.class).source(),
                        v -> v, (v1, v2) -> v1));*//*
    }
*/
  /*  @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        orderHandleMap = applicationContext.getBeansOfType(HanderService.class);
    }*/


    @PostConstruct
    void init() {
        handlersMap = applicationContext.getBeansOfType(HandlerService.class);
    }

    @Override
    public R handler(ApiCommonModel params, String body, HttpServletRequest request) {

        if (handlersMap.size() == 0) {//不用担心为空，即使没有spring也会返回一个空对象

            return R.fail(1000, "系统错误");
        }

        String method = params.getMethod();
        if (handlersMap.get(method) == null) {

            return R.fail(1001, "方法名错误");
        }

        return handlersMap.get(method).handler(params, body, request);

    }


}
